package com.valveinspectionsys.repair.activity;

import java.io.IOException;

import com.valveinspectionsys.R;
import com.valveinspectionsys.dbhelp.XmlNameHelper;
import com.valveinspectionsys.gridview.ImageSwitcherActivity;
import com.valveinspectionsys.povo.DeviceVo;
import com.valveinspectionsys.povo.RepairVo;
import com.valveinspectionsys.repair.db.RepairDao;
import com.valveinspectionsys.util.CHexConver;
import com.valveinspectionsys.util.SharedPreferenceUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 通过读卡添加维修信息
 * @author King
 *2013-4-27
 */
public class RepairSingleRfidActivity  extends Activity implements OnClickListener {
    public TextView textview1;//设备名称
    public TextView textview2;//设备类型
    public TextView textview3;//设备编号
    public TextView textview4;//设备地址
    public TextView textview5;//设备产商
    public TextView textview6;//安装日期
    
    public Button button1;//点击显示
    public Button button2;//读卡
    public Button button3;//保存
    public Button button4;//拍照
    
    public EditText edit1;//更换部件
    public EditText edit2;//备注
    
    public Spinner spinner;//维修形式
    
    public Dialog  dialog;
    
    public RepairDao  dao;
    public SharedPreferenceUtil  sp;
    public String[] data=new String[]{"请选择","更换部件","更换设备","拆卸设备"};
    public String[] checkdata=null;
    public boolean[] selected=null;
    public String repairtype="请选择";
    
    public long time;
    public boolean isStop=false;
    private String rfidNumber;
    
    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    public String[] gz=new String[]{"请选择","更换部件","更换设备","拆除设备"};
    public String[] copydata=new String[3];//故障类型
    public RepairVo   repair;
    public DeviceVo device;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
	
	super.onCreate(savedInstanceState);
	setContentView(R.layout.repair_single_rfid);
	sp=new SharedPreferenceUtil(this);
	dao=new RepairDao(this, sp.getValue(XmlNameHelper.SqliteName));
	init();
	mAdapter = NfcAdapter.getDefaultAdapter(RepairSingleRfidActivity.this);
	mPendingIntent = PendingIntent.getActivity(RepairSingleRfidActivity.this, 0, new Intent(RepairSingleRfidActivity.this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
	IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
	try {
	    ndef.addDataType("*/*");
	    mFilters = new IntentFilter[] { ndef, };
	    mTechLists = new String[][] { new String[] { NfcV.class.getName() }, new String[] { MifareClassic.class.getName() } };

	} catch (MalformedMimeTypeException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
    }

    public void init(){
	checkdata=new String[]{"环境问题","外观问题","外泄露问题","开关不灵活","内泄露问题","出水问题","压力问题","排气问题"};
	 selected = new boolean[checkdata.length];
	    	for (int i = 0; i < selected.length; i++) {
				selected[i] = false;
			}

	textview1=(TextView)findViewById(R.id.repair_single_rfid_devicename);
	textview2=(TextView)findViewById(R.id.repair_single_rfid_devicetype);
	textview3=(TextView)findViewById(R.id.repair_single_rfid_devicenumber);
	textview4=(TextView)findViewById(R.id.repair_single_rfid_deviceadds);
	textview5=(TextView)findViewById(R.id.repair_single_rfid_producers);
	textview6=(TextView)findViewById(R.id.repair_single_rfid_InstallationDate);
	button1=(Button)findViewById(R.id.repair_single_rfid_clickview);
	button2=(Button)findViewById(R.id.repair_single_rfid_tag);
	button3=(Button)findViewById(R.id.repair_single_rfid_save);
	button4=(Button)findViewById(R.id.repair_single_rfid_paizhao);
	button1.setOnClickListener(this);
	button2.setOnClickListener(this);
	button3.setOnClickListener(this);
	button4.setOnClickListener(this);
	edit1=(EditText)findViewById(R.id.repair_single_rfid_reParts);
	edit2=(EditText)findViewById(R.id.repair_single_rfid_remark);
	spinner=(Spinner)findViewById(R.id.repair_single_rfid_repairtype);
	   ArrayAdapter<String>    adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);//设置打开方式
	    spinner.setAdapter(adapter);
	      spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		   repairtype=data[position];
		    
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
		    // TODO Auto-generated method stub
		    
		}
	    });
	
    }
    
    
    public void initData(){
	if(repair==null){
	  
	    edit1.setText("");
	    edit2.setText("");
	    spinner.setSelection(0, true);
	}else{
	    edit1.setText(repair.getReParts());
	    edit2.setText(repair.getRemark());
	    if(!TextUtils.isEmpty(repair.getRepairmethod())){
	  		for(int i=0;i<gz.length;i++){
	  		    if(repair.getRepairmethod().equals(gz[i])){
	  			spinner.setSelection(i, true);
	  		    }
	  		}
	  		
	  	    }else{
	  		spinner.setSelection(0, true);
	  	    }
	}
	if(device==null){
	    textview1.setText("");
	    textview2.setText("");
	    textview3.setText("");
	    textview4.setText("");
	    textview5.setText("");
	    textview6.setText("");
	}else{
	    textview1.setText(device.getUseStatus());
	    textview2.setText(device.getDeviceType());
	    textview3.setText(device.getDeviceNumber());
	    textview4.setText(device.getDeviceAdds());
	    textview5.setText(device.getProducers());
	    textview6.setText(device.getInstallationDate());
	}
    }
    
    @Override
    public void onClick(View v) {
	 switch (v.getId()) {
	case R.id.repair_single_rfid_clickview:
	       initDialog();
	    break;
	case R.id.repair_single_rfid_tag:
	    isStop=true;
	    time=System.currentTimeMillis();
	    rfidNumber="";
	    new Thread(){

		@Override
		public void run() {
		        if(!TextUtils.isEmpty(rfidNumber)){
		            Message msg=myHandler.obtainMessage();
		            msg.what=1;
		            myHandler.sendMessage(msg);
		            isStop=false;
		        }
		        if(System.currentTimeMillis()-time>10000){
		            Message msg=myHandler.obtainMessage();
		            msg.what=2;
		            myHandler.sendMessage(msg);
		            isStop=false;
		            
		        }
		        try {
			    Thread.sleep(300);
			} catch (InterruptedException e) {
			 
			    e.printStackTrace();
			}
		    super.run();
		}
		
	    }.start();
	    break;
	case R.id.repair_single_rfid_paizhao:
	    if(repair==null){
	 		Toast.makeText(RepairSingleRfidActivity.this, "请读卡确认此设备信息", Toast.LENGTH_SHORT).show();
	 		return;
	 	    }
	    Intent   intent=new Intent(RepairSingleRfidActivity.this, ImageSwitcherActivity.class);
		   intent.putExtra("otherid", repair.getRepairid());
		   intent.putExtra("devicelistid", device.getDeviceListId());
		   intent.putExtra("status", "3");
		   startActivityForResult(intent, 2);
	    
	    break;
	case R.id.repair_single_rfid_save:
	    if(repair==null){
		Toast.makeText(RepairSingleRfidActivity.this, "请读卡确认此设备信息", Toast.LENGTH_SHORT).show();
		return;
	    }
	    if(repairtype.equals("请选择")){
		Toast.makeText(RepairSingleRfidActivity.this, "请选择维修方式", Toast.LENGTH_SHORT).show();
		return;
	    }
	    if(!isSelectFault()){
		Toast.makeText(RepairSingleRfidActivity.this, "请选择故障类型", Toast.LENGTH_SHORT).show();
		return;
	    }
	    if(TextUtils.isEmpty(edit1.getEditableText().toString())){
		Toast.makeText(RepairSingleRfidActivity.this, "请填写更换设备或更新部件", Toast.LENGTH_SHORT).show();
		return;
	    }
	 boolean b=   dao.insertDeviceData(device.getDeviceId(), repairtype, faultStr(selected), edit1.getEditableText().toString(),
		    edit2.getEditableText().toString(), "1");
	 if(b){
	     Toast.makeText(RepairSingleRfidActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
	 }else{
	     Toast.makeText(RepairSingleRfidActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
	 }
	    break;
	default:
	    break;
	}
	
    }
    @Override
    protected void onPause() {

	mAdapter.disableForegroundDispatch(this);

	super.onPause();
    }

    @Override
    protected void onResume() {
	mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);

	super.onResume();
    }

    @Override
    protected void onNewIntent(Intent intent) {
	if (!isStop) {
	    return;
	}

	if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
	    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
	    for (String tech : tagFromIntent.getTechList()) {
		System.out.println(tech);
	    }
	    time = System.currentTimeMillis();
	    MifareClassic mf = MifareClassic.get(tagFromIntent);
	    if (mf != null) {

		boolean auth = false;
		try {
		    mf.connect();
		    auth = mf.authenticateSectorWithKeyA(0, MifareClassic.KEY_DEFAULT);// 获取第一个扇区权限
		    if (auth) {
			byte[] date = mf.readBlock(0);// 读取block 0
			rfidNumber = CHexConver.bytesToHexStrings(date);
			Message msg = myHandler.obtainMessage();
			msg.what = 1;
			msg.obj = rfidNumber;
			myHandler.sendMessage(msg);
		    }

		} catch (IOException e) {

		    e.printStackTrace();
		} finally {
		    try {
			mf.close();
		    } catch (IOException e) {

			e.printStackTrace();
		    }
		}

	    }
	    NfcV nf = NfcV.get(tagFromIntent);
	    if (nf != null) {
		rfidNumber = CHexConver.bytesToHexStrings(nf.getTag().getId());
		Message msg = myHandler.obtainMessage();
		msg.what = 1;
		msg.obj = rfidNumber;
		myHandler.sendMessage(msg);
	    }

	}

	super.onNewIntent(intent);
    }
     Handler  myHandler=new Handler(){

	@Override
	public void handleMessage(Message msg) {
	     if(msg.what==1){
		device=dao.queryRfidDevice(rfidNumber, null, false);
		 if(device==null){
		     Toast.makeText(RepairSingleRfidActivity.this, "没有找到此设备的维修单", Toast.LENGTH_SHORT).show();
		     return;
		 }
		 repair=dao.queryRepair(null,device.getDeviceId());
		 faultboolean(repair.getFaultType());
		 initData();
	     }
	    super.handleMessage(msg);
	}
	 
     };
    public void initDialog(){
	
	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    
    	builder.setTitle("故障类型");
    	builder.setMultiChoiceItems(checkdata, selected, new OnMultiChoiceClickListener() {
	    
	    @Override
	    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
		selected[which]=isChecked;
		
	    }
	});
    	builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
	    
	    @Override
	    public void onClick(DialogInterface dialog, int which) {
		
		
	    }
	});
    	builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
	    
	    @Override
	    public void onClick(DialogInterface dialog, int which) {
		
		
	    }
	});
      dialog=builder.create();
      dialog.show();

    }
    
    /**
     * 得到故障类型String
     * @param bo
     * @return
     */
    public String faultStr(boolean[] bo){
	String str="";
	for(int i=0;i<bo.length;i++){
	    if(bo[i]){
		str=str+"1,";
	    }else{
		str=str+"0,";
	    }
	}
	return str.substring(0, str.length()-1);
	
    }
    
    /**
     * 将故障类型String转为每一个选项boolean值
     * @param info
     * @return
     */
    public boolean[]  faultboolean(String info){
	  if(!TextUtils.isEmpty(info)&&info.indexOf(",")>0){
	      String[] str=info.split(",");
	      for(int i=0;i<str.length;i++){
		  if(str[i].equals("1")){
		      selected[i]=true;
		  }
	      }
	  }
	
	return selected;
	
    }
    
    
    /**
     * 判断是否选择了故障类型
     * @return
     */
    public boolean isSelectFault(){
	  boolean b=false;
	 
	  for(int i=0;i<selected.length;i++){
	      if(selected[i]){
		  return true;
	      }
	  }
	return b;
    }
    
    
    @Override
    protected void onDestroy() {
	dao.close();
	super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	  if(requestCode==2){
	      if(resultCode==RESULT_OK){
		  dao.modifyCopystatus(repair.getRepairid(), "1");
	      }else{
		  dao.modifyCopystatus(repair.getRepairid(), "0");
	      }
	  }
	super.onActivityResult(requestCode, resultCode, data);
    }

  
    
}
